package com.gzw.shop.utils;

import android.content.Context;
import android.util.SparseArray;

import com.gzw.shop.bean.ShoppingCart;
import com.gzw.shop.bean.Wares;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by JACKYGUO on 2017-03-10.
 * <p>
 * 数据存储
 */

public class CartProvider {

    public static final String CART_JSON = "cart_json";

    private SparseArray<ShoppingCart> datas = null;
    private Context mContext;

    public CartProvider(Context context) {
        datas = new SparseArray<>(10);
        mContext = context;
        LocalToSparse();
    }

    public void put(ShoppingCart cart) {
        ShoppingCart temp = datas.get(cart.getId().intValue());
        if (temp != null) {
            temp.setCount(temp.getCount() + 1);
        } else {
            temp = cart;
            temp.setCount(1);
        }
        datas.put(cart.getId().intValue(), temp);
        commit();
    }

    //代码重构
    public void put(Wares wares) {
        ShoppingCart cart = new ShoppingCart();
        cart.setId(wares.getId());
        cart.setPrice(wares.getPrice());
        cart.setName(wares.getName());
        cart.setDescription(wares.getDescription());
        cart.setImgUrl(wares.getImgUrl());
        put(cart);
    }


    public void update(ShoppingCart cart) {
        datas.put(cart.getId().intValue(), cart);
        commit();
    }

    public void delete(ShoppingCart cart) {
        datas.delete(cart.getId().intValue());
        commit();
    }

    public void deleteAll() {
        datas.clear();
        commit();
    }


    public List<ShoppingCart> getAll() {
        return getDataFromLocal();
    }

    public List<ShoppingCart> getDataFromLocal() {

        List<ShoppingCart> carts = null;
        String json = (String) SPUtils.get(mContext, CART_JSON, "");
        if (json != null) {
            carts = GsonUtils.getObjectList(json, ShoppingCart.class);
        }
        return carts;
    }


    //更新SP文件数据
    public void commit() {
        List<ShoppingCart> carts = sparseToList();
        SPUtils.put(mContext, CART_JSON, GsonUtils.GsonString(carts));
    }

    private List<ShoppingCart> sparseToList() {

        int size = datas.size();
        List<ShoppingCart> list = new ArrayList<>(size);
        for (int i = 0; i < size; i++) {

            list.add(datas.valueAt(i));
        }
        return list;
    }

    //把本地数据保存到SparseArray对象
    public void LocalToSparse() {

        List<ShoppingCart> list = getDataFromLocal();
        if (list != null && list.size() != 0)
            for (ShoppingCart cart : list) {
                datas.put(cart.getId().intValue(), cart);
            }
    }

}
